﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Football.Models;
using Football.ViewModels;

namespace Football.Controllers
{
    public class HomeController : Controller
    {

        FootballEntities footballDB = new FootballEntities();

        public ActionResult Index()
        {
            var game = footballDB.Games
                        .OrderBy(g => g.GameStartDate)
                        .First();

            GameViewModel gvm = new GameViewModel(game);

            return View(gvm);
        }

        [AllowAnonymous]
        [HttpPost]
        public ActionResult Index(GameViewModel gvm)
        {

            var currentDate = DateTime.Now;

            var game = footballDB.Games
                   .OrderBy(g => g.GameStartDate)
                   .First();

            switch (game.GamePlayers.Count)
            {
                case 1:
                    gvm.PlayerCountTitle = game.GamePlayers.Count + " person so far!";
                    break;
                default:
                    gvm.PlayerCountTitle = game.GamePlayers.Count + " people so far!";
                    break;
            }

            gvm.StartDate = String.Format("{0:dddd d MMMM}", game.GameStartDate);

            gvm.StartTime = String.Format("{0:h tt}", game.GameStartDate);

            if (ModelState.IsValid)
            {
                GamePlayer newPlayer = new GamePlayer();

                newPlayer.CreationDate = currentDate;
                newPlayer.Name = System.Globalization.CultureInfo.CurrentUICulture.TextInfo.ToTitleCase(gvm.NewPlayerName.ToLower());
                newPlayer.GameId = game.GameId;
                newPlayer.GamePlayerStatusId = 1;

                footballDB.GamePlayers.Add(newPlayer);

                footballDB.SaveChanges();

                return RedirectToAction("Index", "Home");
            }

            // If we got this far, something failed, redisplay form
            return View(gvm);

        }

        public ActionResult PlayerList(int id)
        {
            var game = footballDB.Games.Find(id);

            GameViewModel gvm = new GameViewModel(game);

            return PartialView("_PlayerList", gvm);
        }

    }
}
